<?php
set_time_limit(300);
defined('IN_PHPCMS') or exit('No permission resources.');
// 模型缓存路径
define('CACHE_MODEL_PATH', CACHE_PATH . 'caches_model' . DIRECTORY_SEPARATOR . 'caches_data' . DIRECTORY_SEPARATOR);
// 定义在单独操作内容的时候，同时更新相关栏目页面
define('RELATION_HTML', true);

pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_sys_class('form', '', 0);
pc_base::load_app_func('util');
pc_base::load_sys_class('format', '', 0);

/**
 * 商品分类管理
 */
class goods_type extends admin
{

    private $db;

    public $siteid;

    public function __construct()
    {
        parent::__construct();
        $this->db = pc_base::load_model('goods_type_model');
        $this->siteid = get_siteid();
    }

    /**
     * 分类列表
     */
    public function index()
    {
        $show_pc_hash = '';
        $tree = pc_base::load_sys_class('tree');
        $models = getcache('model','commons');
        $sitelist = getcache('sitelist','commons');
        $category_items = array();
        foreach ($models as $modelid=>$model) {
            $category_items[$modelid] = getcache('category_items_'.$modelid,'commons');
        }
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ','&nbsp;&nbsp;&nbsp;├─ ','&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $categorys = array();
        //读取缓存
        $result = $this->db->select(' status <> 2 AND siteid = '.$this->siteid);
        $show_detail = count($result) < 500 ? 1 : 0;
        $parentid = $_GET['parentid'] ? intval($_GET['parentid']) : 0;
        $html_root = pc_base::load_config('system','html_root');
        $types = array(0 => L('category_type_system'),1 => L('category_type_page'),2 => L('category_type_link'));
        if(!empty($result)) {
            foreach($result as $r) {
                $r['str_manage'] = '';
                if(!$show_detail) {
                    if($r['parentid']!=$parentid) continue;
                    $r['parentid'] = 0;
                    $r['str_manage'] .= '<a href="?m=goods&c=goods_type&a=index&parentid='.$r['id'].'&pc_hash='.$_SESSION['pc_hash'].'">'.L('manage_sub_category').'</a> | ';
                }
                $r['str_manage'] .= '<a href="?m=goods&c=goods_type&a=add&parentid='.$r['id'].'&pc_hash='.$_SESSION['pc_hash'].'">'.L('add_sub_category').'</a> | ';
                
                $r['str_manage'] .= '<a href="?m=goods&c=goods_type&a=edit&id='.$r['id'].'&pc_hash='.$_SESSION['pc_hash'].'">'.L('edit').'</a> | <a href="javascript:confirmurl(\'?m=goods&c=goods_type&a=delete&id='.$r['id'].'\',\''.L('confirm',array('message'=>addslashes($r['cn_name']))).'\')">'.L('delete').'</a> ';
                $r['status'] = $r['status'] == 0?'禁用':'可用';
                $r['display_icon'] = $r['parentid'] ? '' : ' <img src ="'.IMG_PATH.'icon/gear_disable.png" title="'.L('not_display_in_menu').'">';
                $categorys[$r['id']] = $r;
            }
        }

        $str  = "<tr>
                    <td align='center'>\$id</td>
                    <td align='left'>\$spacer\$cn_name\$display_icon</td>
                    <td align='center'>\$en_name</td>
                    <td align='center'>\$create_time</td>
                    <td align='center'>\$status</td>
                    <td align='center'>\$str_manage</td>
                </tr>";
        $tree->init($categorys);
        $categorys = $tree->get_tree(0, $str);
        //$big_menu = array('javascript:window.top.art.dialog({id:\'add\',iframe:\'?m=goods&c=goods_type&a=add'.'\', title:\''.L('add_type_good').'\', width:\'700\', height:\'350\'}, function(){var d = window.top.art.dialog({id:\'add\'}).data.iframe;var form = d.document.getElementById(\'dosubmit\');form.click();return false;}, function(){window.top.art.dialog({id:\'add\'}).close()});void(0);', L('add_type_good'));
        include $this->admin_tpl('type');
    }

    /**
     * 添加分类
     */
    function add() {
        $siteid=$this->get_siteid();
        if(isset($_POST['dosubmit'])) {
            $param=$this->check($_POST['goods']);
            $id = $this->db->insert($param);
            if ($id) {

                //记录行为日志
                $log_content = '<span style="color:green;">添加商品分类</span>[新生成分类id：'.$id.'，分类中文名称：'.$param['cn_name'].']';
                $this->manage_admin_log($log_content);

                showmessage(L('operation_success'), '?m=goods&c=goods_type&a=index');
            } else {
                showmessage(L('operation_failure'), HTTP_REFERER);
            }
        } else {
            $show_validator = $show_scroll = true;
            $select_categorys = $this->db->getTypes($_GET['parentid']);
            $models = pc_base::load_config('model_config');
            $typekey=$this->key;
            include $this->admin_tpl('type_add');
        }
    }

    /**
     * 分类修改
     */
    public function edit()
    {
        if (! isset($_GET['id']) || empty($_GET['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = intval($_GET['id']);
        if (isset($_POST['dosubmit']) && ! empty($_POST['dosubmit'])) {
            $goods = $this->check($_POST['goods'], 'edit');
            $ids = $this->db->update($goods, array('id' => $id,'siteid' => $this->siteid));
            if ($ids) {

                //记录行为日志
                $log_content = '<span style="color:blue;">修改商品分类</span>[分类id：'.$id.'，分类中文名称：'.$param['cn_name'].']';
                $this->manage_admin_log($log_content);

                showmessage(L('operation_success'), '?m=goods&c=goods_type&a=index');
            } else {
                showmessage(L('operation_failure'), HTTP_REFERER);
            }
        } else {
            $show_validator = '';
            $info = $this->db->get_one(array('id'=>$id, 'siteid'=>$this->siteid));
            $select_categorys = $this->db->getTypes($info['parentid']);
            $models = pc_base::load_config('model_config');
            $typekey=$this->key;
            include $this->admin_tpl('type_edit');
        }
    }

    /**
     * 分类删除
     */
    public function delete()
    {
        if (! isset($_GET['id']) || empty($_GET['id'])) {
            showmessage(L('illegal_parameters'), HTTP_REFERER);
        } else {
            $id = intval($_GET['id']);
            if ($id < 1)
                return false;
            $result = $this->db->update(array('status'=>2), array('id' => $id,'siteid' => $this->siteid));

            //记录行为日志
            $log_content = '<span style="color:red;">删除商品分类</span>[分类id：'.$id.']';
            $this->manage_admin_log($log_content);

            if ($result) {
                showmessage(L('operation_success'), HTTP_REFERER);
            } else {
                showmessage(L("operation_failure"), HTTP_REFERER);
            }
        }
    }

    /**
     * 表单验证
     * 
     * @param array $data
     *            表单传递的值
     * @param string $a
     *            add/edit添加操作时，自动加上默认值
     */
    private function check($data, $a = 'add')
    {
        if ($a == 'add') {
            $data['siteid'] = $this->siteid;
            $data['create_time'] = date('Y-m-d H:i:s');
            $data['created_by'] = $_SESSION['userid'];
        } else {
            $data['update_time'] = date('Y-m-d H:i:s');
            $data['updated_by'] = $_SESSION['userid'];
        }
        return $data;
    }
}